import { request } from '@/api/request';
import { useRequest } from 'ahooks';
import { TradeDictList } from './interface';
//平台拥有的全部的所属行业
export function useTradeData() {
  return useRequest(
    async () => {
      const { data } = await request<{ tradeDict: TradeDictList }>({
        url: '/account/ent/api/typeConfig/safeTradeDict',
      });

      data.tradeDict.unshift({ tradeDictName: '全部', tradeDictCode: '' });
      return data.tradeDict.map((v) => ({
        label: v.tradeDictName,
        value: v.tradeDictCode,
      }));
    },
    {
      cacheKey: 'TradeDict',
      staleTime: -1,
    },
  );
}

//企业的所属行业
export function useEntHaveTradeData(entId: string) {
  return useRequest(async () => {
    const { data } = await request<{ newBelongIndustry: string }>({
      url: '/account/ent/Ent/api/Enterprise/GetSafeEntBaseInfo.htm',
      params: {
        entId,
      },
    });
    return data.newBelongIndustry ? data.newBelongIndustry.split(',') : [];
  });
}

export function useEntTradeData(entId: string) {
  const { data = [] } = useTradeData(); //平台拥有的全部的所属行业
  const entData = useEntHaveTradeData(entId); //企业拥有的行业
  if (entData.data?.length) {
    //如果企业有所属行业 就展示企业拥有的
    const trade = [];
    for (let i = 0; i < entData.data.length; i++) {
      for (let j = 0; j < data.length; j++) {
        if (entData.data[i] == data[j].value) {
          trade.push({ label: data[j].label, value: data[j].value });
          break;
        }
      }
    }
    trade.unshift({ label: '全部', value: '' });
    return trade;
  } else {
    //如果企业没有所属行业就展示所有的
    return data;
  }
}
